<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage show-footer>
        <div>
            <n-form ref="form"
                    :model="searchCondition"
                    :show-require-mark="false"
                    label-align="right"
                    label-placement="left"
                    label-width="80px">
                <div>
                    <div class="grid md:flex md:flex-wrap md:gap-x-1">
                        <n-form-item style="width: 200px">
                            <label style="width: 90px">客户姓名：</label>
                            <n-input style="width: 150px;" placeholder="输入客户姓名" v-model:value="searchCondition.customerName"></n-input>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px;width: 200px">
                            <label style="width: 130px">订单状态：</label>
                            <n-select v-model:value="searchCondition.status"
                                      :options="statusOptions"
                            ></n-select>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px;width: 200px">
                          <label style="width: 100px">物流商：</label>
                          <n-select v-model:value="searchCondition.logisticsProviderId"
                                    :options="logisticsOptions"
                          />
                        </n-form-item>
                        <n-form-item style="margin-left: 10px;width: 210px;">
                            <label style="width: 120px">促销活动：</label>
                            <n-select v-model:value="searchCondition.salePromotionId"
                                      :options="saleOptions"
                            ></n-select>
                        </n-form-item>
                        <n-form-item style="margin-left: 10px;">
                            <n-button type="primary" @click="searchByCondition">筛选</n-button>
                        </n-form-item>
                      <n-form-item style="margin-left: 10px;">
                        <n-button type="primary" @click="test">添加客户订单</n-button>
                      </n-form-item>
                      <n-form-item  style="margin-left: 10px">
                        <n-button type="error" @click="deleteSelectCustomerOrders">批量删除</n-button>
                      </n-form-item>
                      <n-form-item style="margin-left: 10px">
                        <n-button type="primary" @click="exportListInfo">导出</n-button>
                      </n-form-item>
                    </div>
                </div>
            </n-form>
      </div>
      <AddCustomerOrder
          :statuses="filteredStatus"
          :storeCommodity="storeCommodity"
          :option="option"
          :shops="shops"
          :logisticsProviders="filteredlogistics"
          :customers="customers"
          :salePromotions="filteredSaleOptions"
          @update-page="searchByCondition"
          :show="showForm"
          :onClose="handleClose" />
      <UpdateCustomerOrder
          :statuses="filteredStatus"
          :storeCommodity="storeCommodity"
          :option="option"
          :shops="shops"
          :logisticsProviders="filteredlogistics"
          :customers="customers"
          :salePromotions="filteredSaleOptions"
          @update-page="searchByCondition"
          :show1="showForm1"
          :onClose="handleClose"
          :attribute="currentAttribute"
      />
      <CustomerOrderSTATUS
          :statusOptions="filteredStatus"
          :storeCommodity="storeCommodity"
          :option="option"
          :shops="shops"
          :logisticsProviders="filteredlogistics"
          :customers="customers"
          :salePromotions="filteredSaleOptions"
          @update-page="searchByCondition"
          :show1="showForm2"
          :onClose="handleClose"
          :attribute="currentAttribute"
      />
      <n-data-table
          remote
          :single-line="false"
          ref="table"
          :columns="columns"
          :data="customerOrderList"
          :loading="loading"
          :pagination="paginationReactive"
          :row-key="rowKey"
          @update:checked-row-keys="handleCheck"
      />
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import {h, onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import OrderActions from './components/order-actions.vue';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import AddCustomerOrder from "./components/customerOrder-add.vue"
import UpdateCustomerOrder from "./components/customerOrder-edit.vue"
import CustomerOrderSTATUS from "./components/customerOrder-status.vue"
import {NTag} from "naive-ui";
import PurchaseActions from "@/views/admin/category/components/category-actions.vue";

const userStore = useUserStore()
const router = useRouter()
const rules = ref(null)
const customerOrderInfoRef = ref(null)
const loading = ref(true)
const customerOrderList = ref([])
const showForm=ref(false);
const showForm1=ref(false);
const showForm2=ref(false);
const option = ref([])
const currentAttribute = ref(null); // 当前编辑的属性
const test = () => {
  showForm.value = true;
};
let total = 0
const checkedRowKeysRef = ref([]);
const handleCheck = (rowKeys) => {
  checkedRowKeysRef.value = rowKeys;
}
const handleClose = () => {
  showForm.value = false;
  showForm1.value = false;
  showForm2.value = false;
};
const searchCondition = ref({
  customerName: "",
  status: "全部",
  logisticsProviderId: -1,
  salePromotionId: -1,
});
const logisticsOptions = ref([])
logisticsOptions.value.push({
  label: '全部',
  value: -1,
})
const saleOptions = ref([])
saleOptions.value.push({
  label: '全部',
  value: -1,
})
const storeCommodity = ref([])
const shops = ref([])
const customers = ref([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 50,
  showSizePicker: true,
  pageSizes: [50, 100, 150],
  itemCount: 0,
  prefix: () => {
    return '查询出 ' + total + '条记录';
  },
  onChange: (page) => {
    paginationReactive.page = page;
    queryByPage()
  },
  onUpdatePageSize: (pageSize) => {
    paginationReactive.pageSize = pageSize;
    paginationReactive.page = 1;
    queryByPage()
  }
});

const statusOptions=ref([
  {
    label: '全部',
    value: '全部',
  },
  {
    label: '未发货',
    value: '未发货',
  },
  {
    label: '运输中',
    value: '运输中',
  },
  {
    label: '已完成',
    value: '已完成',
  },
  {
    label: '待售后',
    value: '待售后',
  },
  {
    label: '已退款',
    value: '已退款',
  }
])
const searchByCondition = async () => {
  loading.value = true
  try {
    paginationReactive.page = 1;
    const res = await api.findPageCustomerOrder({
      params: {
        customerName:searchCondition.value.customerName,
        status: searchCondition.value.status,
        logisticsProviderId: searchCondition.value.logisticsProviderId.toString(),
        salePromotionId:searchCondition.value.salePromotionId.toString(),
        pageNum: paginationReactive.page,
        pageSize: paginationReactive.pageSize,
      }
    })
    if(res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
      customerOrderList.value = res.data.records.map((item,i)=>{
        return {...item,
          colId: baseCount + i + 1,
        }
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("查询客户订单失败！")
  }finally{
    loading.value = false
  }
}

const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: '40',
  },
  {
    key: 'id',
    title: '编号',
    width: '50',
  },
  {
    key: 'productName',
    title: '产品名称',
    width: '200',
    render(row) {
      if (row["productId"] === null) {
        return "无"
      }
      return row["productName"]
    }
  },
  {
    key: 'quantity',
    title: '数量',
    width: '50',
  },
  {
    key: 'price',
    title: '金额',
    width: '50',
  },
  {
    key: 'currency',
    title: '币种',
    width: '50',
  },
  {
    key: 'shopName',
    title: '店铺',
    width: '85',
    render(row) {
      if (row["shopId"] === null) {
        return "无"
      }
      return row["shopName"]
    }
  },
  {
    key: 'logisticsProviderName',
    title: '物流商',
    width: '85',
    render(row) {
      if (row["logisticsProviderId"] === null) {
        return "无"
      }
      return row["logisticsProviderName"]
    }
  },
  {
    key: 'customerName',
    title: '客户',
    width: '70',
    render(row) {
      if (row["customerId"] === null) {
        return "无"
      }
      return row["customerName"]
    }
  },
  {
    key: 'customerPhone',
    title: '客户电话',
    width: '70',
  },
	{
		key: 'customerNation',
		title: '国家',
		width: '100',
	},
  {
    key: 'customerAddress',
    title: '客户地址',
    width: '100',
  },
  {
    key: 'salePromotionName',
    title: '促销活动',
    width: '70',
    render(row) {
      if (row["salePromotionId"] === null) {
        return "无"
      }
      return row["salePromotionName"]
    }
  },
  {
    key: 'status',
    title: '订单状态',
    width: '70',
    render(row) {
      if (row.status === "未发货") {
        return h(
            NTag,
            {
              type: 'info',
              bordered: false,
              style: {cursor: 'pointer'},
              onClick: () => handleStatusClick(row)
            },
            {
              default: () => '未发货'
            }
        );
      } else if (row.status === "运输中") {
        return h(
            NTag,
            {
              type: 'info',
              bordered: false,
              style: {cursor: 'pointer'},
              onClick: () => handleStatusClick(row)
            },
            {
              default: () => '运输中'
            }
        );
      } else if (row.status === "已完成") {
        return h(
            NTag,
            {
              type: 'success',
              bordered: false,
            },
            {
              default: () => '已完成'
            }
        );
      } else if (row.status === "待售后") {
        return h(
            NTag,
            {
              type: 'info',
              bordered: false,
              style: {cursor: 'pointer'},
              onClick: () => handleStatusClick(row)
            },
            {
              default: () => '待售后'
            }
        );
      } else if (row.status === "已退款") {
        return h(
            NTag,
            {
              type: 'error',
              bordered: false,
              style: {cursor: 'pointer'},
            },
            {
              default: () => '已退款'
            }
        );
      }
    }
  },
  {
    key: 'createTime',
    title: '创建时间',
    width: '70',
  },
  {
    key: 'actions',
    title: '操作',
    width: '120',
    render(row) {
      if (row.status !== "已完成" && row.status !== "已退款") {
        return h(
            PurchaseActions,
            {
              onClickDelete: () => onDeleteCustomerOrder(row),
              onClickEdit: () => onEditCustomerOrder(row),
            }
        );
      }
    }
  },
]
let filteredStatus
const handleStatusClick = async (purchaseOrder) => {
  currentAttribute.value = purchaseOrder; // 设置当前编辑的属性
  showForm2.value = true; // 显示编辑窗口
  if (purchaseOrder.status === "未发货"){
    filteredStatus=ref([
      {
        label: '未发货',
        value: '未发货',
      },
      {
        label: '已退款',
        value: '已退款',
      }
    ])
  }
  else if (purchaseOrder.status === "运输中"){
    filteredStatus=ref([
      {
        label: '已完成',
        value: '已完成',
      },
      {
        label: '已退款',
        value: '已退款',
      }
    ])
  }
  else{
    filteredStatus=ref([
      {
        label: '已完成',
        value: '已完成',
      }
    ])
  }
}

const filteredlogistics = computed(() => logisticsOptions.value.filter(logistics => logistics.value !== -1));
const filteredSaleOptions = computed(() => saleOptions.value.filter(saleOption => saleOption.value !== -1));

const onDeleteCustomerOrder = async (customerOrder) => {
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前客户订单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const {id} = customerOrder
      loading.value = true
      try {
        const res = await api.deleteCustomerOrder({id})
        if(res.code === 200) {
          $message.success("删除客户订单成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除客户订单失败！")
      }finally{
        loading.value = false
      }
    }
  })
}
const deleteSelectCustomerOrders = () => {
  if(checkedRowKeysRef.value.length <= 0) {
    console.log(checkedRowKeysRef.value.length)
    $message.error("当前并未选择客户订单！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选客户订单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      loading.value = true
      try {
        const res = await api.deleteCustomerOrders({params:{ids}})
        if(res.code === 200) {
          $message.success("删除所选客户订单成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选客户订单失败！")
      }finally{
        loading.value = false
      }
    },
  })
}
const onEditCustomerOrder = async (customerOrder) => {
  currentAttribute.value = customerOrder; // 设置当前编辑的属性
  showForm1.value = true; // 显示编辑窗口
  currentAttribute.value.planTime = customerOrder.planTime;
}
const queryByPage = async () => {
  loading.value = true
  try {
    const res = await api.findPageCustomerOrder(
        {
          params: {
            pageNum: paginationReactive.page,
            pageSize: paginationReactive.pageSize,
          }
        })
    if (res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      const baseCount = (paginationReactive.page - 1) * paginationReactive.pageSize
      customerOrderList.value = res.data.records.map((item, i) => {
        return {
          ...item,
          colId: baseCount + i + 1,
        }
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取订单失败！")
  }finally{
    loading.value = false
  }
}
const queryLogisticsProviderList = async () => {
  loading.value = true
  try {
    const res = await api.findAllLogisticsProvider(
        {
          params: {
            role: 'SUPERADMIN'
          }
        }
    )
    if(res.code === 200) {
      res.data.map((item)=>{
        logisticsOptions.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取物流商列表信息失败！")
  }finally{
    loading.value = false
  }
}
const querySalePromotionList = async () => {
  loading.value = true
  try {
    const res = await api.findAllSalePromotionActivities(
        {
          params: {
            role: 'SUPERADMIN'
          }
        }
    )
    if(res.code === 200) {
      res.data.map((item)=>{
        saleOptions.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取促销活动列表信息失败！")
  }finally{
    loading.value = false
  }
}
const queryProductsList = async () => {
  loading.value = true
  try {
    const res = await api.findAllInventory()
    if(res.code === 200) {
      res.data.map((item)=>{
        storeCommodity.value.push({
          label: item.productName,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取产品列表信息失败！")
  }finally{
    loading.value = false
  }
}
const queryShopsList = async () => {
  loading.value = true
  try {
    const res = await api.findAllShop()
    if(res.code === 200) {
      res.data.map((item)=>{
        shops.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取店铺列表信息失败！")
  }finally{
    loading.value = false
  }
}
const queryCustomersList = async () => {
  loading.value = true
  try {
    const res = await api.findAllCustomer(
        {
          params: {
            role: 'SUPERADMIN'
          }
        }
    )
    if(res.code === 200) {
      res.data.map((item)=>{
        customers.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取客户列表信息失败！")
  }finally{
    loading.value = false
  }
}
const exportListInfo = async () => {
  const res = await api.exportCustomerOrderList({
    customerName: searchCondition.value.customerName,
    status: searchCondition.value.status,
    logisticsProviderId: searchCondition.value.logisticsProviderId.toString(),
    salePromotionId: searchCondition.value.salePromotionId.toString(),
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if (contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else {
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.style.display = 'none'
    const href = window.URL.createObjectURL(blob)
    elink.href = href
    elink.download = fileName
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const sub = async ()=>{
  customerOrderInfoRef.value?.validate(async (errors) => {
    await queryByPage(1)
  })
}

const rowKey = (rowData) => {
  return rowData.id
}
onMounted(()=>{
  queryByPage()
  queryLogisticsProviderList()
  querySalePromotionList()
  queryProductsList()
  queryShopsList()
  queryCustomersList()
})
</script>
<style scoped>


</style>
